package schoolWork;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {
    private JTextField num1Field, num2Field, resultField;

    public Calculator() {
        setTitle("计算");
        setLayout(new FlowLayout());

        num1Field = new JTextField(10);
        num2Field = new JTextField(10);
        resultField = new JTextField(10);
        resultField.setEditable(false);

        JButton addButton = new JButton("加");
        JButton subButton = new JButton("减");
        JButton mulButton = new JButton("乘");
        JButton divButton = new JButton("除");

        addButton.addActionListener(this);
        subButton.addActionListener(this);
        mulButton.addActionListener(this);
        divButton.addActionListener(this);

        add(num1Field);
        add(num2Field);
        add(resultField);
        add(addButton);
        add(subButton);
        add(mulButton);
        add(divButton);

        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int num1 = Integer.parseInt(num1Field.getText());
        int num2 = Integer.parseInt(num2Field.getText());
        int result = 0;

        if (e.getActionCommand().equals("加")) {
            result = num1 + num2;
        } else if (e.getActionCommand().equals("减")) {
            result = num1 - num2;
        } else if (e.getActionCommand().equals("乘")) {
            result = num1 * num2;
        } else if (e.getActionCommand().equals("除")) {
            result = num1 / num2;
        }

        resultField.setText(String.valueOf(result));
    }

    public static void main(String[] args) {
        new Calculator();
    }
}
